<?php
/**
 *
 * Application.php
 * User: kalvin
 * Date: 2018/1/24
 * Time: 下午3:18
 */

namespace core;

use Noodlehaus\Config;


class Application
{
    public static $routeInfo;
    private static $htmlresult;
    /**
     * defDir
     * 定义文件目录的绝对路径方便访问
     */
    public static function denfDir()
    {
        define('ROOT_PATH', dirname(__DIR__) . '/');
        define('CONF_PATH', ROOT_PATH . 'conf/');
        define('RESOURCE',ROOT_PATH.'resource/');
        define('CACHE',ROOT_PATH.'caching/');
    }
    public static function whoops_error()
    {
    //  whoops报错插件
        //根据app.php中的debug判断是否报错
        $bool=\config('app.debug');
        if ($bool){
            $whoops = new \Whoops\Run;
            $errorTitle='框架出错了！';
            $option=new \Whoops\Handler\PrettyPageHandler();
            $option->setPageTitle($errorTitle);
            $whoops->pushHandler($option);
            $whoops->register();
            ini_set('display_error','On');
        }else{
            ini_set('display_error','Off');
        }

    }
    public static function getUrl()
    {

        $dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) {
            include ROOT_PATH.'router/web.php';
        });

// Fetch method and URI from somewhere
        $httpMethod = $_SERVER['REQUEST_METHOD'];
        $uri = $_SERVER['REQUEST_URI'];

// Strip query string (?foo=bar) and decode URI
        if (false !== $pos = strpos($uri, '?')) {
            $uri = substr($uri, 0, $pos);
        }
        $uri = rawurldecode($uri);

        $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
        switch ($routeInfo[0]) {
            case \FastRoute\Dispatcher::NOT_FOUND:
                // ... 404 Not Found
                break;
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                // ... 405 Method Not Allowed
                break;
            case \FastRoute\Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];
                // ... call $handler with $vars
                break;
        }
        self::$routeInfo = $routeInfo;

    }
    public static function setHeader(){
        header('content-type:text/html;charset='.\config('app.charset'));
    }
    /**
     *  分发路由
     */
    public static function Route()
    {
        $routerMessage=explode('@',self::$routeInfo[1]);
        $controller='App\\Controller\\'.$routerMessage[0];
        $action=$routerMessage[1];
        $obj=new $controller;
        self::$htmlresult=$obj->$action();

    }
    public static function send(){
        echo self::$htmlresult;
    }

    public static function run()
    {
        self::denfDir();
        self::setHeader();
        self::whoops_error();
        self::getUrl();
        self::Route();
        self::send();
    }
}